package com.zy.kotlinmvpapp.net

import com.zy.kotlinbaselibrary.log.XLog
import com.zy.kotlinbaselibrary.net.LogInterceptor
import com.zy.kotlinbaselibrary.net.NetProvider
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit

class OkHttpConfig private constructor() {


    companion object {
        val connectTimeoutMills = 10 * 10001L

        val readTimeoutMills = 10 * 10001L

        var okHttpClient: OkHttpClient? = null

        var provider: NetProvider? = null

        val okHttpConfig: OkHttpConfig by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            OkHttpConfig()
        }

    }


    /**
     * 用于在原有的okhttp的配置中，修改某个配置
     * @return
     */
    val okHttpBuild: OkHttpClient.Builder
        get() = if (okHttpClient != null) {
            okHttpClient!!.newBuilder()
        } else OkHttpClient.Builder()

    /**
     * 设置okhttp配置类，这里的配置才是整个项目的主配置
     * @param sProvider
     */
    fun registerProvider(sProvider: NetProvider) {
        OkHttpConfig.provider = sProvider
    }

    fun getOkHttpClient(): OkHttpClient {

        XLog.i("provider:"+provider)

        if (provider == null) {
            throw IllegalStateException("must register provider first")
        }
        if (okHttpClient == null) {
            okHttpClient = configOkHttp()
        }

        return okHttpClient as OkHttpClient
    }

    // 配置okhttp
    private fun configOkHttp(): OkHttpClient {

        val builder = OkHttpClient.Builder()

        provider?.apply {
            // 配置连接时间
            var connectTime = configConnectTimeoutMills()
            if (connectTime == 0L) {
                connectTime = connectTimeoutMills
            }

            // 配置读取时间
            var readTime = configReadTimeoutMills()
            if (readTime == 0L) {
                readTime = readTimeoutMills
            }

            // 配置cookie
            var cookieJar = configCookie()
            if (cookieJar != null) {
                builder.cookieJar(cookieJar)
            }

            // 配置https
            configHttps(builder)

            // 添加拦截器
            val interceptors = configInterceptors()
            interceptors.forEach {
                builder.addInterceptor(it)
            }

            // 添加log拦截器
            if (configLogEnable()) {
                var logInterceptor = LogInterceptor()
                builder.addInterceptor(logInterceptor)
            }

            builder.connectTimeout(connectTime, TimeUnit.MILLISECONDS)
                .readTimeout(readTime, TimeUnit.MILLISECONDS)

        }


        return builder.build()
    }


}
